package com.mallcloud.mall.mall.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mallcloud.mall.common.core.constant.CacheConstants;
import com.mallcloud.mall.common.core.constant.enums.mall.AppSettingEnum;
import com.mallcloud.mall.mall.api.entity.MallAppSettingModel;
import com.mallcloud.mall.mall.mapper.MallAppSettingMapper;
import com.mallcloud.mall.mall.service.MallAppSettingService;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 商城app界面设置
 */
@Service
@AllArgsConstructor
public class MallAppSettingServiceImpl extends ServiceImpl<MallAppSettingMapper, MallAppSettingModel> implements MallAppSettingService {

    @Override
    public IPage<MallAppSettingModel> pageAppSetting(Page page, MallAppSettingModel dto) {
        return this.page(page, Wrappers.query(dto));
    }

    @Override
    @Cacheable(value = CacheConstants.APP_SETTING, key = "#dto.type", unless = "#result.isEmpty()")
    public List<MallAppSettingModel> listAppSetting(MallAppSettingModel dto) {
        if (AppSettingEnum.TypeEnum.TYPE_1.getCode().equals(dto.getType())) {
            Date now = new Date();
            List<MallAppSettingModel> resList = this.list(Wrappers.lambdaQuery(dto)
                    .lt(MallAppSettingModel::getActivityStartTime, now)
                    .gt(MallAppSettingModel::getActivityEndTime, now)
                    .orderByAsc(MallAppSettingModel::getSortOrder)
            );
            return resList;
        }
        List<MallAppSettingModel> resList = this.list(Wrappers.query(dto));
        return resList;
    }

    @Override
    public MallAppSettingModel getAppSettingById(Long id) {
        return this.getById(id);
    }

    @Override
    @CacheEvict(value = CacheConstants.APP_SETTING, key = "#appSetting.type")
    public Boolean saveAppSetting(MallAppSettingModel appSetting) {
        return this.save(appSetting);
    }

    @Override
    @CacheEvict(value = CacheConstants.APP_SETTING, key = "#appSetting.type")
    public Boolean updateAppSetting(MallAppSettingModel appSetting) {
        return this.updateById(appSetting);
    }

    @Override
    @CacheEvict(value = CacheConstants.APP_SETTING, allEntries = true)
    public Boolean removeAppSettingById(Long id) {
        return this.removeById(id);
    }

    @Override
    @CacheEvict(value = CacheConstants.APP_SETTING, allEntries = true)
    public Boolean removeAppSettingByIds(List<Long> ids) {
        return this.removeByIds(ids);
    }
}
